import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import request from '@/utils/request'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      request.post('sso/login', userInfo).then((res) => {
        commit('SET_TOKEN', res)
        setToken(res)
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      request.get('sso/getInfo').then((res) => {
        if (!res) {
          reject('验证失败,请重新登陆!')
        }
        const { roles, admin } = res

        if (!roles || roles.length <= 0) {
          reject('当前登陆用户暂未分配角色，请联系管理员')
        }

        commit('SET_ROLES', roles)
        commit('SET_USER_INFO', admin)
        resolve(res)
      }).catch((err) => {
        reject(err)
      })
    })
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      request.post('sso/logout').then(() => {
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  state,
  mutations,
  actions
}

